package com.seculab.common.util;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class CipherUtil {

	public static Key generateKey(String algorithm) throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
		SecretKey key = keyGenerator.generateKey();
		return key;
	}
	
	public static Key generateKey(String algorithm, byte[] keyData) throws NoSuchAlgorithmException, InvalidKeyException
		, InvalidKeySpecException {
		SecretKeySpec keySpec = new SecretKeySpec(keyData, algorithm);
		return keySpec;
	}
	
	public static String encrypt(String password) throws NoSuchAlgorithmException, InvalidKeyException
		, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
	    byte[] passwordBytes = password.getBytes();
	    int len = passwordBytes.length;
	    byte[] keyBytes = new byte[16];
	    if (len >= 16) {
	        System.arraycopy(passwordBytes, 0, keyBytes, 0, 16);
	    } else {
	        System.arraycopy(passwordBytes, 0, keyBytes, 0, len);
	        for (int i = 0; i < (16 - len); i++) {
	            keyBytes[len + i] = passwordBytes[i % len];
	        }
	    }
	   
	    Key key = generateKey("AES", keyBytes);
	    String transformation = "AES/ECB/PKCS5Padding";
	    Cipher cipher = Cipher.getInstance(transformation);
	    cipher.init(Cipher.ENCRYPT_MODE, key);
	    byte[] plain = password.getBytes();
	    byte[] encrypt = cipher.doFinal(plain);
		
	    return ByteUtils.toHexString(encrypt);
	}
}
